<template>
  <div class="merchant-audit">
    <el-card>
      <div slot="header" class="clearfix">
        <span class="page-title"><i class="el-icon-share"></i> 商家审核管理</span>
        <div class="header-description">
          <span style="font-size: 14px; color: #909399;">业务员提交的商家审核申请，总公司负责审核</span>
        </div>
      </div>
      <div class="search-form">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="审核状态">
            <el-select v-model="searchForm.statue" placeholder="请选择状态" clearable>
              <el-option label="待审核" :value="1"></el-option>
              <el-option label="已通过" :value="2"></el-option>
              <el-option label="已拒绝" :value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开始时间">
            <el-date-picker
              v-model="searchForm.startTime"
              type="date"
              placeholder="选择开始时间"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker
              v-model="searchForm.endTime"
              type="date"
              placeholder="选择结束时间"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <configurable-table
        :columns="tableColumns"
        :data="tableData"
        :loading="loading"
        :show-pagination="true"
        :current-page.sync="pagination.current"
        :page-size.sync="pagination.size"
        :pagination-total="pagination.total"
        @page-change="loadData"
        border
        stripe>
        <!-- 审核状态列 -->
        <template #statue="{ row }">
          <el-tag :type="getStatusType(row.statue)" size="small">
            {{ getStatusText(row.statue) }}
          </el-tag>
        </template>
        <!-- 操作列 -->
        <template #actions="{ row }">
          <div class="action-buttons">
            <!-- 查看按钮 -->
            <div class="button-group primary-group">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleView(row)">
                查看详情
              </el-button>
            </div>
            <!-- 审核按钮组 -->
            <div v-if="row.statue === 1" class="button-group audit-group">
              <el-button
                size="mini"
                type="text"
                class="approve-btn"
                icon="el-icon-check"
                @click="handleApprove(row)">
                通过
              </el-button>
              <el-button
                size="mini"
                type="text"
                class="reject-btn"
                icon="el-icon-close"
                @click="handleReject(row)">
                拒绝
              </el-button>
            </div>
          </div>
        </template>
      </configurable-table>
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog
      title="商家审核详情"
      :visible.sync="detailDialogVisible"
      width="900px"
      custom-class="view-dialog"
      :close-on-click-modal="false">
      <div v-if="detailData" class="detail-content">
        <!-- 审核状态展示 -->
        <div class="status-banner" :class="'status-' + detailData.statue">
          <div class="status-icon">
            <i v-if="detailData.statue === 1" class="el-icon-warning"></i>
            <i v-else-if="detailData.statue === 2" class="el-icon-success"></i>
            <i v-else class="el-icon-error"></i>
          </div>
          <div class="status-info">
            <div class="status-label">审核状态</div>
            <div class="status-value">{{ getStatusText(detailData.statue) }}</div>
          </div>
        </div>

        <!-- 基本信息 -->
        <div class="info-section">
          <div class="section-title">
            <i class="el-icon-user"></i>
            <span>基本信息</span>
          </div>
          <el-row :gutter="20" class="info-row">
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-office-building"></i>
                  商家名称
                </div>
                <div class="info-value">{{ detailData.name }}</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-phone"></i>
                  联系电话
                </div>
                <div class="info-value">{{ detailData.phone }}</div>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20" class="info-row">
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-postcard"></i>
                  身份证号码
                </div>
                <div class="info-value">{{ detailData.idNo }}</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-user-solid"></i>
                  业务员编码
                </div>
                <div class="info-value">{{ detailData.salesmanNo }}</div>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20" class="info-row">
            <el-col :span="24">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-location"></i>
                  详细地址
                </div>
                <div class="info-value">{{ detailData.address }}</div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 业务信息 -->
        <div class="info-section">
          <div class="section-title">
            <i class="el-icon-s-data"></i>
            <span>业务信息</span>
          </div>
          <el-row :gutter="20" class="info-row">
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-lock"></i>
                  锁定用户数量
                </div>
                <div class="info-value">
                  <span class="highlight-number">{{ detailData.lockNumLimit || 0 }}</span> 人
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <div class="info-label">
                  <i class="el-icon-time"></i>
                  申请时间
                </div>
                <div class="info-value">{{ detailData.createTime }}</div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 拒绝原因（如果有） -->
        <div v-if="detailData.reason" class="info-section reason-section">
          <div class="section-title">
            <i class="el-icon-warning-outline"></i>
            <span>拒绝原因</span>
          </div>
          <div class="reason-content">
            {{ detailData.reason }}
          </div>
        </div>

        <!-- 证件图片展示 -->
        <div class="info-section">
          <div class="section-title">
            <i class="el-icon-picture"></i>
            <span>证件资料</span>
          </div>
          <div class="certificate-grid">
            <div v-if="detailData.idCardUrl" class="certificate-card" @click="previewImage(detailData.idCardUrl)">
              <div class="certificate-label">
                <i class="el-icon-postcard"></i>
                身份证正面
              </div>
              <div class="certificate-image">
                <img :src="detailData.idCardUrl" alt="身份证正面">
                <div class="image-overlay">
                  <i class="el-icon-zoom-in"></i>
                  <span>点击预览</span>
                </div>
              </div>
            </div>
            <div v-if="detailData.idCardBackUrl" class="certificate-card" @click="previewImage(detailData.idCardBackUrl)">
              <div class="certificate-label">
                <i class="el-icon-postcard"></i>
                身份证背面
              </div>
              <div class="certificate-image">
                <img :src="detailData.idCardBackUrl" alt="身份证背面">
                <div class="image-overlay">
                  <i class="el-icon-zoom-in"></i>
                  <span>点击预览</span>
                </div>
              </div>
            </div>
            <div v-if="detailData.certificateUrl" class="certificate-card" @click="previewImage(detailData.certificateUrl)">
              <div class="certificate-label">
                <i class="el-icon-document"></i>
                营业执照
              </div>
              <div class="certificate-image">
                <img :src="detailData.certificateUrl" alt="营业执照">
                <div class="image-overlay">
                  <i class="el-icon-zoom-in"></i>
                  <span>点击预览</span>
                </div>
              </div>
            </div>
            <div v-if="detailData.hygienicUrl" class="certificate-card" @click="previewImage(detailData.hygienicUrl)">
              <div class="certificate-label">
                <i class="el-icon-document-checked"></i>
                卫生许可证
              </div>
              <div class="certificate-image">
                <img :src="detailData.hygienicUrl" alt="卫生许可证">
                <div class="image-overlay">
                  <i class="el-icon-zoom-in"></i>
                  <span>点击预览</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="detailDialogVisible = false">
          <i class="el-icon-close"></i>
          关闭
        </el-button>
      </div>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog
      :visible.sync="imagePreviewVisible"
      width="70%"
      custom-class="image-preview-dialog"
      append-to-body>
      <img :src="previewImageUrl" style="width: 100%; display: block;">
    </el-dialog>
  </div>
</template>

<script>
import { getMerchantAuditPage, checkMerchantAudit, getMerchantAuditDetail } from '@/api/aggregation'

export default {
  name: 'MerchantAudit',
  data() {
    return {
      loading: false,
      searchForm: {
        statue: null,
        startTime: '',
        endTime: ''
      },
      tableData: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      // 表格列配置
      tableColumns: [
        { prop: 'id', label: 'ID', minWidth: 80, align: 'center' },
        { prop: 'name', label: '商家名称', minWidth: 150, showOverflowTooltip: true },
        { prop: 'phone', label: '联系电话', minWidth: 140, align: 'center' },
        { prop: 'address', label: '商家地址', minWidth: 200, showOverflowTooltip: true },
        { prop: 'salesmanNo', label: '业务员编码', minWidth: 120, align: 'center' },
        { prop: 'statue', label: '审核状态', minWidth: 100, align: 'center', slot: 'statue' },
        { prop: 'createTime', label: '申请时间', minWidth: 160, align: 'center' },
        { prop: 'actions', label: '操作', minWidth: 150, align: 'center', slot: 'actions', fixed: false }
      ],
      // 对话框相关
      detailDialogVisible: false,
      detailData: null,
      // 图片预览相关
      imagePreviewVisible: false,
      previewImageUrl: ''
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    async loadData() {
      this.loading = true
      try {
        const params = {
          pageIndex: this.pagination.current,
          pageSize: this.pagination.size,
          ...this.searchForm
        }

        const response = await getMerchantAuditPage(params)

        if (response.code === 0) {
          this.tableData = response.data.list || []
          this.pagination.total = response.data.total || 0
        } else {
          this.tableData = []
          this.pagination.total = 0
        }
      } catch (error) {
        Logger.error('加载商家审核数据失败:', error)
        this.tableData = []
        this.pagination.total = 0
      } finally {
        this.loading = false
      }
    },
    getStatusType(status) {
      const types = { 1: 'warning', 2: 'success', 3: 'danger' }
      return types[status] || 'info'
    },
    getStatusText(status) {
      const texts = { 1: '待审核', 2: '已通过', 3: '已拒绝' }
      return texts[status] || '未知'
    },
    handleSearch() {
      this.pagination.current = 1
      this.loadData()
    },
    handleReset() {
      this.searchForm = {
        statue: null,
        startTime: '',
        endTime: ''
      }
      this.loadData()
    },
    async handleApprove(row) {
      try {
        Logger.log('=== 审核通过 ===')
        Logger.log('审核数据:', row)
        Logger.log('审核ID:', row.id)

        const auditData = {
          id: row.id,
          statue: 2, // 通过
          reason: ''  // 拒绝原因（通过时不用传）
        }
        Logger.log('发送的审核数据:', auditData)

        const response = await checkMerchantAudit(auditData)
        Logger.log('审核响应:', response.data)

        if (response.code === 0) {
          this.$message.success('审核通过')
          this.loadData()
        } else {
          this.$message.error(response.msg || '审核失败')
        }
      } catch (error) {
        Logger.error('审核通过失败:', error)
        this.$message.error('审核失败: ' + (error.message || '未知错误'))
      }
    },
    async handleReject(row) {
      this.$prompt('请输入拒绝原因（可选）', '审核拒绝', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入拒绝原因'
      }).then(async ({ value }) => {
        try {
          Logger.log('=== 审核拒绝 ===')
          Logger.log('审核数据:', row)
          Logger.log('审核ID:', row.id)
          Logger.log('拒绝原因:', value)

          const auditData = {
            id: row.id,
            statue: 3, // 拒绝
            reason: value || '' // 拒绝原因
          }
          Logger.log('发送的审核数据:', auditData)

          const response = await checkMerchantAudit(auditData)
          Logger.log('审核响应:', response.data)

          if (response.code === 0) {
            this.$message.success('审核拒绝')
            this.loadData()
          } else {
            this.$message.error(response.msg || '操作失败')
          }
        } catch (error) {
          Logger.error('审核拒绝失败:', error)
          this.$message.error('操作失败: ' + (error.message || '未知错误'))
        }
      }).catch(() => {
        // 用户取消操作
      })
    },

    // 查看详情
    async handleView(row) {
      Logger.log(row)
      try {
        const response = await getMerchantAuditDetail({id:row.id})
        if (response.code === 0) {
          this.detailData = response.data
          this.detailDialogVisible = true
        } else {
          this.$message.error('获取商家详情失败')
        }
      } catch (error) {
        Logger.error('获取商家详情失败:', error)
        this.$message.error('获取商家详情失败')
      }
    },

    // 图片预览
    previewImage(url) {
      this.previewImageUrl = url
      this.imagePreviewVisible = true
    }
  }
}
</script>

<style scoped>
.merchant-audit {
  padding: 20px;
}

/* 页面标题样式 */
.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

/* 头部描述区域 */
.header-description {
  margin-top: 8px;
}

/* 操作按钮样式优化 */
.el-button--mini {
  margin-right: 5px;
  border-radius: 3px;
  font-weight: 500;
}

.el-button--mini:last-child {
  margin-right: 0;
}

/* 搜索表单样式 */
.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

/* 表格样式优化 */
.el-table {
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-table th {
  background: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

/* 分页样式 */
.el-pagination {
  margin-top: 20px;
  text-align: right;
}

/* 状态标签样式优化 */
.el-tag {
  border-radius: 12px;
  font-weight: 500;
}

/* 卡片头部样式 */
.el-card__header {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-bottom: 1px solid #dee2e6;
  border-radius: 8px 8px 0 0;
  padding: 20px 24px;
}

.el-card__header .clearfix {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 操作按钮样式优化 */
.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-items: center;
  padding: 8px 0;
}

.button-group {
  display: flex;
  gap: 12px;
  justify-content: center;
  align-items: center;
}

.audit-group {
  /* 审核操作按钮组 */
  padding-top: 4px;
  border-top: 1px solid #f0f0f0;
}

.action-buttons .el-button {
  margin: 0;
  padding: 6px 12px;
  font-size: 12px;
  border-radius: 4px;
  transition: all 0.3s ease;
  min-width: 60px;
}

.action-buttons .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.approve-btn {
  color: #67C23A !important;
  font-weight: 500;
}

.approve-btn:hover {
  background-color: #f0f9ff;
  color: #67C23A !important;
}

.reject-btn {
  color: #F56C6C !important;
  font-weight: 500;
}

.reject-btn:hover {
  background-color: #fef0f0;
  color: #F56C6C !important;
}

/* 基础按钮悬停效果 */
.primary-group .el-button:hover {
  background-color: #f5f7fa;
  color: #409EFF;
}

/* 表格样式优化 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-table th {
  background-color: #fafafa;
  color: #303133;
  font-weight: 600;
}

.el-table td {
  padding: 12px 0;
}

.el-table .cell {
  padding: 0 12px;
}

.el-card__header .page-title {
  color: #2c3e50;
  font-size: 22px;
  font-weight: 700;
  letter-spacing: 0.5px;
}
</style>
